/* api */
import { updateTranslate } from '@src/api/AIApi'
/* hooks */
import { 
  useSettingGPTRobotAppEditStatus, 
  useFetchSettingGPTRobotApp 
} from '@gpt/hooks/intelligent-qa'
import { useInitXiaoBaoChat } from '@gpt/hooks/robot'
import { useLoading } from '@hooks/useLoading'
/* model */
import MsgModel from '@model/MsgModel'
import { UpdateTranslateModel } from '@model/param/in/AI'
/* vue */
import { computed, Ref, ref } from 'vue'
/* util */
import { message } from '@src/util/message'

function useSettingGPTRobotAppTranslate() {
  
  const {
    initChat
  } = useInitXiaoBaoChat()
  
  const {
    robotId,
    robotAppId
  } = useSettingGPTRobotAppEditStatus()
  
  const {
    loading: fetchGptRobotAppLoading,
    fetchGptRobotApp,
    gptRobotApp
  } = useFetchSettingGPTRobotApp()
  
  const {
    loading: fetchUpdateTranslateLoading,
    isSuccess: fetchUpdateTranslateIsSuccess,
    fetchUpdateTranslate
  } = useFetchUpdateTranslate()
  
  const loading = computed(() => {
    return (
      fetchGptRobotAppLoading.value
      || fetchUpdateTranslateLoading.value
    )
  })
  
  const onFetchGptRobotAppHandler = () => {
    return fetchGptRobotApp({
      id: robotAppId.value,
      robotId: robotId.value
    })
  }
  
  const initialize = () => {
    onFetchGptRobotAppHandler()
  }
  
  const onUpdateRobotAppTranslateHandler = (translateToLanguage: string) => {
    
    const params: UpdateTranslateModel = {
      robotId: robotId.value,
      robotAppId: robotAppId.value,
      translateToLanguage
    }
    
    return fetchUpdateTranslate(params).then(isSuccess => {
      if (isSuccess) {
        initChat()
      }
    })
    
  }
  
  return {
    initialize,
    loading,
    robotId,
    gptRobotApp,
    onFetchGptRobotAppHandler,
    onUpdateRobotAppTranslateHandler
  }
}

/**
 * @description 更新 小宝 GPT 机器人 应用 智能翻译
 */
function useFetchUpdateTranslate() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const isSuccess: Ref<boolean> = ref(false)
  
  const fetchUpdateTranslate = (params: UpdateTranslateModel) => {
    
    setLoading()
    
    return (
      updateTranslate(params).then(result => {
        
        isSuccess.value = MsgModel.isSuccess(result)
        
        if (isSuccess.value) {
          // 
        } else {
          message.error(MsgModel.getMessage(result))
        }
        
        return isSuccess.value
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    isSuccess,
    fetchUpdateTranslate
  }
}

export {
  useSettingGPTRobotAppTranslate
}